//
//  LCVerificationCodeVC.m
//  LongChain
//
//  Created by FengZi on 2018/4/11.
//  Copyright © 2018年 FengZi. All rights reserved.
//

#import "LCVerificationCodeVC.h"
#import "LCUserModel.h"
@interface LCVerificationCodeVC ()<UITextFieldDelegate>


@property (weak, nonatomic) IBOutlet UIView *codeBaseView;

@property (weak, nonatomic) IBOutlet UILabel *desLabel;

@property (weak, nonatomic) IBOutlet UILabel *countDownLabel;
@property (weak, nonatomic) IBOutlet UIButton *countdownTip;

@property (weak, nonatomic) IBOutlet UITextField *firstCode;

@property (weak, nonatomic) IBOutlet UITextField *secondCode;

@property (weak, nonatomic) IBOutlet UITextField *thirdCode;

@property (weak, nonatomic) IBOutlet UITextField *fouthCode;

@end

@implementation LCVerificationCodeVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self customTranslucentNavigationBar];
    [self registNotification];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    [self.firstCode becomeFirstResponder];

    
    NSString *tip = [NSString stringWithFormat:@"验证码已发送至手机:  %@",_phoneNum];
    self.desLabel.text = tip;
    LCLog(@"_phoneNum = %@",_phoneNum);
    self.codeBaseView.userInteractionEnabled = NO;
    UIImageView *bgImage = [[UIImageView alloc]initWithFrame:self.view.frame];
    bgImage.image = [UIImage imageNamed:@"publicBackground"];
    [self.view addSubview:bgImage];
    [self.view insertSubview:bgImage atIndex:0];
    
    
    NSString *desStr = [NSString stringWithFormat:@"60秒后可再次获取验证码"];
    self.countDownLabel.text = desStr;
    [self countDownWithTime:60];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self removeNotification];
    
}

- (void)registNotification {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(registCodeChange) name:UITextFieldTextDidChangeNotification object:nil];

}

- (void)removeNotification {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}
#pragma mark - - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (string.length > 1) {
        return NO;
    }
    
    CGFloat time = 0;
    if ([string isEqualToString:@""]) {
        //  删除操作
        if (self.fouthCode.text.length == 0) {
            
            //  删除第三格
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.secondCode becomeFirstResponder];
            });

             //  还没有输入完整 那么可能是停留在第四个之前的输入框
            if (self.thirdCode.text.length == 0) {
                 //  删除第二个
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.firstCode becomeFirstResponder];
                });
            }
        }else{
            
            self.fouthCode.text = @"";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.thirdCode becomeFirstResponder];

            });
        }
    }else{
        //  输入操作
        if (self.fouthCode.text.length > 0) {
            return NO;
        }
        if (self.fouthCode.text.length == 1){

        }else if (self.thirdCode.text.length == 1){
            [self.fouthCode becomeFirstResponder];
        }else if (self.secondCode.text.length == 1){
            
            [self.thirdCode becomeFirstResponder];
            
        }else{
            
            if (self.firstCode.text.length > 0) {
                [self.secondCode becomeFirstResponder];
            }
        }
    }
    return YES;

}

#pragma mark - - Action
- (IBAction)sendRegistCode:(id)sender {
    
    LCLog(@"发送验证码");
    NSDictionary *sendRegistCode = @{@"phone":self.phoneNum};
    [[LCNetwork shareInstance]lc_postNetworkWithRUL:@"/api/v0/sms" parameter:sendRegistCode responseSuccess:^(id resultCode, id resultParameter) {
        
        self.countdownTip.userInteractionEnabled = NO;

        LCLog(@"resultCode = %@ resultParameter = %@",resultCode,resultParameter);
        NSString *code = [NSString stringWithFormat:@"%@",resultParameter[@"code"]];
        self.registCode = code;
        NSString *idStr = [NSString stringWithFormat:@"%@",resultParameter[@"id"]];
        NSString *token = [NSString stringWithFormat:@"%@",resultParameter[@"token"]];
        
        [LCUserModel userModelManager].userid = token;
        LCLog(@"idStr = %@ token = %@",idStr,token);
        
    } responseFail:^(id resultCode, NSError *error) {
        
        [self showHint:@"网络异常,请稍后再试"];
    }];


    
}

- (void)countDownWithTime:(NSInteger)time {
    __block NSInteger countDown = time;
    WS(weakSelf);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        countDown --;
        LCLog(@"%ld",(long)countDown);
        if (countDown > 1) {
            NSString *desStr = [NSString stringWithFormat:@"%ld秒后可再次获取验证码",(long)countDown];
            weakSelf.countDownLabel.text = desStr;

            [weakSelf countDownWithTime:countDown];

        }else{
            weakSelf.countdownTip.userInteractionEnabled = YES;
            weakSelf.countDownLabel.text = @"重新发送验证码";
        }
    });

}
- (void)registCodeChange {
    
    if (self.fouthCode.text.length == 1) {
        LCLog(@"提交验证码");
        if (self.registCode.length > 4) {
            self.registCode = [self.registCode substringWithRange:NSMakeRange(0, 4)];
        }
        
        NSString *registCodeStr =[NSString stringWithFormat:@"%@%@%@%@",self.firstCode.text,self.secondCode.text,self.thirdCode.text,self.fouthCode.text];

        if ([registCodeStr isEqualToString:self.registCode]) {
            [self performSegueWithIdentifier:@"showPasswordSetting" sender:self];

        }else{
            [self showHint:@"请输入正确的验证码"];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"showPasswordSetting"]) {
        

        id registSettingPass = segue.destinationViewController;
        [registSettingPass setValue:self.phoneNum forKey:@"registPhone"];
        [registSettingPass setValue:self.registCode forKey:@"registCode"];
        [registSettingPass setValue:@([self.type integerValue]) forKey:@"settingPasswordType"];
         
    }
}


@end
